package com.mofee.util;

import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import okhttp3.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * @author Arvin
 */
public final class HttpUtils {

    public static String decodeUrl(String url) {
        try {
            return URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return url;
        }
    }

    public static String get(String url) {
        return get(url, "UTF-8");
    }

    public static String get(final String url, final String encoding) {
        return get(url, encoding, false);
    }

    /**
     * 发送HTTP GET请求
     *
     * @param url 请求URL
     * @return 返回请求结果
     */
    public static String get(final String url, final String encoding, final boolean retry) {
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        try (Response execute = httpClient.newCall(request).execute()) {
            ResponseBody body = execute.body();
            return body == null ? null : new String(body.bytes(), encoding);
        } catch (SocketTimeoutException e) {
            if (retry) {
                return get(url, encoding, retry);
            }
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> void getAsync(@NotNull final String url, @Nullable final Consumer<String> success, @Nullable final Consumer<T> fail) {
        OkHttpClient httpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().url(url).get().build();
        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (fail != null) {
                    fail.accept(null);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (success != null) {
                    ResponseBody body = response.body();
                    success.accept(body == null ? "" : body.string());
                }
            }
        });

        try (Response execute = httpClient.newCall(request).execute()) {
            ResponseBody body = execute.body();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String post(String url) {

        return null;
    }
}
